package cn.xiuxius.embedded.toolwindow;

import cn.xiuxius.embedded.toolwindow.dirvermanager.DriveManagerToolWindow;
import cn.xiuxius.embedded.toolwindow.flashtool.FlashingToolWindow;
import cn.xiuxius.embedded.toolwindow.projecttool.ProjectToolWindow;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.*;

import org.jetbrains.annotations.NotNull;

import java.io.File;

public class EasySTCToolWindowFactory implements ToolWindowFactory, DumbAware {

    @Override
    public boolean shouldBeAvailable(@NotNull Project project) {
        return hasEasyStcConfig(project);
    }

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        if (!hasEasyStcConfig(project)) {
            return;
        }

        // 串口工具
        SerialToolWindow serialToolWindow = new SerialToolWindow();
        Content serialContent = ContentFactory.getInstance().createContent(
                serialToolWindow.getMainPanel(), "串口工具", false);
        toolWindow.getContentManager().addContent(serialContent);

        // 烧录工具
        FlashingToolWindow advFlashToolWindow = new FlashingToolWindow(project);
        Content advFlashContent = ContentFactory.getInstance().createContent(
                advFlashToolWindow, "烧录工具", false);
        toolWindow.getContentManager().addContent(advFlashContent);

        // 驱动管理
        DriveManagerToolWindow driveManagerToolWindow = new DriveManagerToolWindow(project);
        Content driveManagerToolWindowContent = ContentFactory.getInstance().createContent(
                driveManagerToolWindow, "驱动管理", false);
        toolWindow.getContentManager().addContent(driveManagerToolWindowContent);

        // 项目工具
        ProjectToolWindow projectToolWindow = new ProjectToolWindow(project);
        Content projectToolWindowContent = ContentFactory.getInstance().createContent(
                projectToolWindow, "项目工具", false);
        toolWindow.getContentManager().addContent(projectToolWindowContent);

    }

    private boolean hasEasyStcConfig(Project project) {
        String basePath = project.getBasePath();
        if (basePath == null) return false;

        File configFile = new File(basePath, "easy-stc.yml");
        return configFile.exists();
    }
}
